package com.oss.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.oss.bean.UpLoadResult;
import com.oss.config.AliyunConfig;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.UUID;
@Service
public class FileUpLoadService {

    @Autowired
    private AliyunConfig aliyunConfig;
    @Autowired
    private OSSClient  ossClient;

    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{ ".jpg", ".jpeg", ".png"};

    public UpLoadResult upload(MultipartFile multipartFile){

        UpLoadResult upLoadResult = new UpLoadResult();

        //限制大小
        long size = multipartFile.getSize();

        int legalSize = 1024*1024*5;

        if(size>legalSize) {
            upLoadResult.setStatus("error");
            upLoadResult.setResponse("必须小于5M");
            return  upLoadResult;
        }

        // 校验图片格式
        boolean  isLegal = false;
        for (String type:IMAGE_TYPE){
            if(StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(),type)){
                isLegal = true;
                break;
            }
        }

        if (!isLegal){
            upLoadResult.setStatus("error");
            upLoadResult.setResponse("必须为 jpg、png 或者 jpeg类型");
            return  upLoadResult;
        }
        String fileName = multipartFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        try {
            ossClient.putObject(aliyunConfig.getBucketName(),filePath,new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            // 上传失败
            upLoadResult.setStatus("error");
            return  upLoadResult;
        }
        upLoadResult.setStatus("done");
        upLoadResult.setName(aliyunConfig.getUrlPrefix()+filePath);
        upLoadResult.setUid(filePath);
        return  upLoadResult;
    }

    // 生成不重复的文件路径和文件名
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + UUID.randomUUID().toString() + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }

    public UpLoadResult delete(String fileName){

        UpLoadResult upLoadResult = new UpLoadResult();

        ossClient.deleteObject(aliyunConfig.getBucketName(),fileName);

        upLoadResult.setStatus("success");
        upLoadResult.setResponse("删除成功");

        return upLoadResult;
    }

    public void download(HttpServletRequest request, HttpServletResponse response,String fileName){
        try {
            // 从阿里云进行下载
            OSSObject ossObject = ossClient.getObject(aliyunConfig.getBucketName(),fileName);
            // 已缓冲的方式从字符输入流中读取文本，缓冲各个字符，从而提供字符、数组和行的高效读取
            BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));

            InputStream inputStream = ossObject.getObjectContent();

            //缓冲文件输出流
            BufferedOutputStream outputStream=new BufferedOutputStream(response.getOutputStream());
            //通知浏览器以附件形式下载
            // response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
            // 为防止 文件名出现乱码
            response.setContentType("application/doc");
            final String userAgent = request.getHeader("USER-AGENT");
            if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
                fileName = URLEncoder.encode(fileName,"UTF-8");
            }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            }else{
                fileName = URLEncoder.encode(fileName,"UTF-8");//其他浏览器
            }
            response.addHeader("Content-Disposition", "attachment;filename=" +fileName);//这里设置一下让浏览器弹出下载提示框，而不是直接在浏览器中打开


            byte[] car = new byte[1024];
            int L;

            while((L = inputStream.read(car)) != -1){
                if (car.length!=0){
                    outputStream.write(car, 0,L);
                }
            }

            if(outputStream!=null){
                outputStream.flush();
                outputStream.close();
            }


        } catch (IOException e) {
            e.printStackTrace();

        }
    }


}

